package com.vvvtimes.demo.util;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * OkHttpClient封装
 */
@Slf4j
public class OkHttp3ClientManager {

    private static OkHttp3ClientManager mInstance;
    private OkHttpClient mOkHttpClient;

    private OkHttp3ClientManager() {
        mOkHttpClient = new OkHttpClient.Builder().readTimeout(30, TimeUnit.SECONDS) // 读取超时
                .connectTimeout(10, TimeUnit.SECONDS) // 连接超时
                .writeTimeout(60, TimeUnit.SECONDS) // 写入超时
                .build();
    }

    public static OkHttp3ClientManager getInstance() {
        if (mInstance == null) {
            synchronized (OkHttp3ClientManager.class) {
                if (mInstance == null) {
                    mInstance = new OkHttp3ClientManager();
                }
            }
        }
        return mInstance;
    }

    /**
     * 构造get方法连接拼加参数
     *
     * @param mapParams
     * @return
     */
    private String buildUrlParams(Map<String, Object> mapParams) {
        String strParams = "";
        if (mapParams != null) {
            Iterator<String> iterator = mapParams.keySet().iterator();
            String key = "";
            while (iterator.hasNext()) {
                key = iterator.next().toString();
                strParams += "&" + key + "=" + mapParams.get(key);
            }
        }

        return strParams;
    }

    /**
     * 构造post请求参数-form形式
     *
     * @param bodyParamMap
     * @return
     */
    private RequestBody buildRequestBodyForm(Map<String, String> bodyParamMap) {
        RequestBody body = null;
        // 创建请求的参数body
        FormBody.Builder builder = new FormBody.Builder();
        // 遍历key
        if (null != bodyParamMap) {
            for (Map.Entry<String, String> entry : bodyParamMap.entrySet()) {
                log.info("Key = " + entry.getKey() + ", Value = " + entry.getValue());
                builder.add(entry.getKey(), entry.getValue());
            }
        }
        body = builder.build();
        return body;
    }

    /**
     * 构造请求头
     *
     * @param headerMap
     * @return
     */
    private Headers buildHeaders(Map<String, String> headerMap) {
        Headers.Builder builder = new Headers.Builder();
        // 构造header
        // 遍历key
        if (null != headerMap) {
            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                log.info("Key = " + entry.getKey() + ", Value = " + entry.getValue());
                builder.add(entry.getKey(), entry.getValue());
            }
        }
        Headers build = builder.build();
        return build;
    }


    /**
     * HTTP接口-GET方式，返回为String
     * 请求参数形式为params形式
     *
     * @param reqUrl      请求地址
     * @param urlParamMap 请求参数map
     * @return String 请求结果
     */
    public String sendGet(String reqUrl, Map<String, Object> urlParamMap) throws IOException {
        return sendGet(reqUrl, urlParamMap, null);
    }

    /**
     * get请求
     *
     * @param reqUrl      请求地址
     * @param urlParamMap 请求参数map
     * @param headers     请求头map
     * @return 请求结果
     */
    public String sendGet(String reqUrl, Map<String, Object> urlParamMap, Map<String, String> headers) throws IOException {
        String UrlParams = buildUrlParams(urlParamMap);
        String URL = reqUrl;
        if(StringUtils.isNotBlank(UrlParams)){
           URL = reqUrl + "?" + UrlParams;
        }
        Request request = new Request.Builder()
                .url(URL)
                .headers(buildHeaders(headers))
                .get()
                .build();
        Response response;
        String result;
        try {
            response = mOkHttpClient.newCall(request).execute();
            result = response.body().string();
        } catch (IOException e) {
            throw new IOException("DATA", e);
        }
        return result;
    }

    /**
     * 表单形式post请求
     *
     * @param url  请求地址
     * @param form post请求参数
     * @return 请求结果
     */
    public String sendPostForm(String url, Map<String, String> form) throws IOException {
        return sendPostForm(url, form, null);
    }

    /**
     * 表单形式post请求
     *
     * @param url     请求地址
     * @param form    post请求参数
     * @param headers 请求头
     * @return String 请求结果
     */
    public String sendPostForm(String url, Map<String, String> form, Map<String, String> headers) throws IOException {
        RequestBody requestBody = buildRequestBodyForm(form);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .headers(buildHeaders(headers))
                .build();
        Call call = mOkHttpClient.newCall(request);
        //返回请求结果
        try (Response response = call.execute()) {
            return response.body().string();
        } catch (IOException e) {
            throw new IOException(e);
        }
    }

    /**
     * HTTP接口-POST方式，请求参数形式为body-json形式
     * 不带header
     *
     * @param url
     * @param jsonString
     * @return String
     */
    public String sendPostJson(String url, String jsonString) throws IOException {
        return sendPostJson(url, jsonString, null);
    }

    /**
     * HTTP接口-POST方式，请求参数形式为body-json形式
     *
     * @param url
     * @param jsonString
     * @param headers
     * @return String
     */
    public String sendPostJson(String url, String jsonString, Map<String, String> headers) throws IOException {
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonString);
        Request request = new Request.Builder()
                .post(body)
                .headers(buildHeaders(headers))
                .url(url)
                .build();
        Call call = mOkHttpClient.newCall(request);
        //返回请求结果
        try {
            Response response = call.execute();
            return response.body().string();
        } catch (IOException e) {
            throw new IOException(e);
        }
    }

    /**
     * HTTP接口-POST方式，请求参数形式为body-json形式
     * 返回为bean 参数responseType 为 XXX.class
     *
     * @param url
     * @param jsonString
     * @param responseType
     * @return <T>
     */
    public <T> T sendPostJsonObject(String url, String jsonString, Class<T> responseType) throws IOException {
        String s = sendPostJson(url, jsonString);
        if (s != null && !s.isEmpty()) {
            T t = JSONObject.parseObject(s, responseType);
            return t;
        }
        return null;
    }


    /**
     * HTTP接口-POST方式，请求参数形式为body-json形式
     * 返回为bean 参数responseType 为 XXX.class
     *
     * @param url
     * @param responseType
     * @return <T>
     */
    public <T> T sendGetObject(String url, Class<T> responseType) throws IOException {
        Map<String, String> headers = new HashMap<>();
        //headers.put("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36");
        String s = sendGet(url,null,null);
        if (s != null && !s.isEmpty()) {
            T t = JSONObject.parseObject(s, responseType);
            return t;
        }
        return null;
    }


    /**
     * HTTP接口-POST方式，请求参数形式为body-json形式
     * 返回为bean 为type 为 new TypeReference<T>(){} 支持bean嵌套泛型
     *
     * @param url
     * @param jsonString
     * @param type
     * @return String
     */
    public <T> T sendPostJsonObject(String url, String jsonString, TypeReference<T> type) throws IOException {
        String s = sendPostJson(url, jsonString);
        if (s != null && !s.isEmpty()) {
            T t = JSONObject.parseObject(s, type);
            return t;
        }
        return null;
    }

    /**
     * HTTP接口-POST方式，请求参数形式为body-json形式
     * 返回为List<bean> 参数responseType 为 XXX.class
     *
     * @param url
     * @param jsonString
     * @param responseType
     * @return String
     */
    public <T> List<T> sendPostJsonList(String url, String jsonString, Class<T> responseType) throws IOException {
        String s = sendPostJson(url, jsonString);
        if (s != null && !s.isEmpty()) {
            List<T> ts = JSONObject.parseArray(s, responseType);
            return ts;
        }
        return null;
    }

    public static void main(String[] args) throws IOException {
        /*String url = "http://localhost:8080/user/addUser";
        UserDTO build = UserDTO.builder()
                .username("user99")
                .password("password2")
                .build();
        String jsonString = JSONObject.toJSONString(build);
        RestResponse<Long> restResponse = com.example.platformservice.util.OkHttp3ClientManager.getInstance().sendPostJsonObject(url, jsonString, new TypeReference<RestResponse<Long>>() {
        });
        log.info(restResponse.getResult() + "");*/
    }


}
